<?php
Yii::import('application.modules.menu.utililies.menuService');

class RecipiedetailController extends ControllerBase
{
	public function init() {
            parent::init();
            $this->defaultAction = 'admin';
        }

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Recipiedetail;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Recipiedetail']))
		{
//                    var_dump($_POST['Recipiedetail']['materialid']);
			$model->attributes=$_POST['Recipiedetail'];          //materialid     
                        foreach ($_POST['Material'] as $m => $value){
                            foreach ($value as $k => $v){
                                $quantity = preg_replace('/\\s/', '', $v);
                                if (intval($quantity) != 0){
                                    //insert into material request detail
                                    $model=new Recipiedetail;
                                    $model->recipieid = $_POST['Recipiedetail']['materialid']; //column recipieid in recipiedetail named materialid in create form
                                    $model->quantity = $quantity;
                                    $model->materialid = $k;
                                    $model->save();
                                }                                
                            }
                        }			
		}
                
                $materialList = Material::model()->findAll();
		$this->render('create',array(
                    'model'=>$model,
                    'materialList' => $materialList
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
                $model= Recipiedetail::model()->find(array(
                    'condition' => 'recipieid = :id',
                    'params' => array(
                        ':id' => $id,
                    )
                ));

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

                if(isset($_POST['Recipiedetail']))
		{
			$model->attributes=$_POST['Recipiedetail'];          //materialid   
                        foreach ($_POST['Material'] as $m => $value){
                            foreach ($value as $k => $v){
                                $quantity = preg_replace('/\\s/', '', $v);                                
                                if (intval($quantity) != 0){
                                    $recipieDetailModel = Recipiedetail::model()->find(array(
                                        'condition' => 'recipieid = :id AND materialid = :materialid',
                                        'params' => array(
                                            ':id' => $_POST['Recipiedetail']['materialid'],
                                            ':materialid' => $k,
                                        )
                                    ));  
                                    
                                    //update recipie materials
                                    if($recipieDetailModel !== null){
                                        $recipieDetailModel->updateAll(
                                            array(
                                                'quantity' => $quantity,
                                                'materialid' => $k
                                            ),
                                            'recipieid = ' . $_POST['Recipiedetail']['materialid'] . ' AND materialid = ' . $k);
                                        
                                    }else{  //insert new recipie material
                                      $recipieDetailModel = new Recipiedetail;
                                      $recipieDetailModel->materialid = $k;
                                      $recipieDetailModel->quantity = $quantity;
                                      $recipieDetailModel->recipieid = $id;
                                      $recipieDetailModel->save();
                                    }                                    
                                }
                            }
                        }			
		}

                //load material in recipie
                $presetMaterial = Recipiedetail::model()->findAll(array(
                    'condition' => 'recipieid = :id',
                    'params' => array(
                        ':id' => $id,
                    )
                ));
                
                //load active key of recipie
                $active = Recipie::model()->find(array(
                    'condition' => 'recipieid = :id',
                    'params' => array(
                        ':id' => $id,
                    )
                ));
                
                
                $materialList = Material::model()->findAll();
		$this->render('update',array(
                    'model'=>$model,
                    'materialList' => $materialList,
                    'presetMaterial' => $presetMaterial,
                    'active' => $active->active,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
//			$this->loadModel($id)->delete();
                        $recipie = Recipie::model()->find(array(
                            'condition' => 'recipieid = :id',
                            'params' => array(
                                ':id' => $id,
                            )
                        ));
                        $recipie->active = 0;
                        $recipie->update('active');

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Recipiedetail');
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Recipiedetail('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Recipiedetail']))
			$model->attributes=$_GET['Recipiedetail'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Recipiedetail::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='Recipiedetail-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
